﻿namespace My.Hydrator.Helpers
{
    using System;

    using System.Linq.Expressions;
    using System.Reflection;

    public static class ReflectionHelper
    {
        public static string GetFullPropertyName<TClass, TResult>(Expression<Func<TClass, TResult>> expression)
        {
            string name = string.Empty;

            Expression ex = expression.Body;

            do
            {
                var body = (MemberExpression)ex;
                var memberName = body.Member.Name;

                name = string.IsNullOrEmpty(name) ? memberName : string.Format("{0}.{1}", memberName, name);

                if (body.Expression as ParameterExpression != null)
                {
                    break;
                }

                ex = body.Expression;
            }
            while (true);

            return name;
        }

        public static string GetFullPropertyName(PropertyInfo propertyInfo)
        {
            string name = propertyInfo.Name;

            var propertyType = propertyInfo.PropertyType.BaseType;

            while (propertyType != typeof(object))
            {
                var propertyName = propertyType.Name;

                name = string.IsNullOrEmpty(name) ? propertyName : string.Format("{0}.{1}", propertyName, name);

                propertyType = propertyInfo.DeclaringType;
            }

            return name;
        }

        public static string GetClassName<T>(Expression<Func<T>> expression)
        {
            Expression ex = expression.Body;

            var result = string.Empty;

            do
            {
                if (ex as ConstantExpression != null)
                {
                    break;
                }

                var body = (MemberExpression)ex;
                result = ex.Type.FullName;

                ex = body.Expression;
            }
            while (true);

            return result;
        }
    }
}
